/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.henryschein.mmvvcc.dao;

import com.henryschein.mmvvcc.model.User;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author obelog
 */
@Repository
public class UserDao {
    
    @PersistenceContext
    private EntityManager entityManager;
    
    @SuppressWarnings("unchecked")
    public List<User> getUsers() {
        return entityManager.createQuery("select u from User u").getResultList();
    }
    
    public User find(Long id) {
        return entityManager.find(User.class, id);
    }
    
    @Transactional
    public User save(User user) {
        if (user.getId() == null) {
            entityManager.persist(user);
            return user;
        } else {
            return entityManager.merge(user);
        }
    }

    @Transactional
    public void remove(User user) {
        entityManager.remove(entityManager.getReference(User.class, user.getId()));
    }
}
